﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.IO;
using Sinacor.OMM.Logging;
using System.Diagnostics;

namespace Sinacor.OMM.ConnectionManagerSTM
{
    public class StmLastIdFileManager : IDisposable
    {
        const int MSG_ID_SIZE = 30;

        private FileStream _fileStream;
        string _filePath;

        public StmLastIdFileManager(string filePath)
        {
            _filePath = filePath;
            _fileStream = null;
        }

        public void OpenOrCreateFile()
        {
            try
            {

                if (!Directory.Exists(Path.GetDirectoryName(_filePath)))
                    Directory.CreateDirectory(Path.GetDirectoryName(_filePath));

                if(!IsFileOpen())
                    _fileStream = new FileStream(_filePath, FileMode.OpenOrCreate);
            }
            catch (System.IO.IOException ex)
            {
                EventLog.WriteEntry(LogSources.ReceptorService, string.Concat(ex.Message, " ", ex.StackTrace), EventLogEntryType.Error);
            }
            catch (Exception ex)
            {
                EventLog.WriteEntry(LogSources.ReceptorService, string.Concat(ex.Message, " ", ex.StackTrace), EventLogEntryType.Error);
                //throw ex;
            }

        }

        public void Dispose()
        {
            try
            {
                if (_fileStream != null)
                {
                    _fileStream.Flush();
                    _fileStream.Close();
                    _fileStream.Dispose();
                }
            }
            catch (Exception ex)
            {
                EventLog.WriteEntry(LogSources.ReceptorService, string.Concat(ex.Message, " ", ex.StackTrace), EventLogEntryType.Error);
                throw ex;
            }

        }

        public void WriteLastMsgId(string lastMsgId)
        {
            try
            {
                if (_fileStream == null) OpenOrCreateFile();

                _fileStream.Position = 0;
                _fileStream.Write(Encoding.Default.GetBytes(lastMsgId), 0, lastMsgId.Length);
                _fileStream.Flush();
            }
            catch (System.IO.IOException ex)
            {
                EventLog.WriteEntry(LogSources.ReceptorService, string.Concat(ex.Message, " ", ex.StackTrace), EventLogEntryType.Error);
            }
            catch (Exception ex)
            {
                EventLog.WriteEntry(LogSources.ReceptorService, string.Concat(ex.Message, " ", ex.StackTrace), EventLogEntryType.Error);
            }
        }

        public string ReadLastMsgId()
        {

            string ret;
            byte[] buffer;

            try
            {
                buffer = new byte[MSG_ID_SIZE];

                if (_fileStream != null && _fileStream.Length <= MSG_ID_SIZE)
                {
                    _fileStream.Read(buffer, 0, MSG_ID_SIZE);
                    _fileStream.Flush();
                    ret = Encoding.Default.GetString(buffer);
                }
                else
                {
                    Dispose();
                    File.Delete(_filePath);
                    OpenOrCreateFile();
                    ret = string.Empty;
                }
            }
            catch (Exception ex)
            {
                EventLog.WriteEntry(LogSources.ReceptorService, string.Concat(ex.Message, " ", ex.StackTrace), EventLogEntryType.Error);
                throw ex;
            }

            return ret;
        }

        public void Delete()
        {

            try
            {
                Dispose();
                File.Delete(_filePath);
            }
            catch (Exception ex)
            {
                EventLog.WriteEntry(LogSources.ReceptorService, string.Concat(ex.Message, " ", ex.StackTrace), EventLogEntryType.Error);
                throw ex;
            }
        }

        private bool IsFileOpen()
        {
            bool fileOpened = false;
            try
            {
                System.IO.FileStream fs = System.IO.File.OpenWrite(_filePath);
                fs.Close();
            }
            catch (System.IO.IOException ex)
            {
                fileOpened = true;
            }

            return fileOpened;
        }
    }
}
